package com.lt.androidsocketserver.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author LiuTong
 */
public class HttpThread implements Runnable {
    private Socket mSocket;
    private HttpCallback httpCallback;
    public HttpThread(Socket socket, HttpCallback httpCallback) {
        this.mSocket = socket;
        this.httpCallback = httpCallback;
    }

    @Override
    public void run() {
        /****
         * 读取客户端数据数据
         * 更具业务操作
         * 返回数据
         */

        try {
            /***
             * 提高I/O效率，有缓存
             * 更具业务进行操作
             */
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(
                            mSocket.getInputStream(),StandardCharsets.UTF_8));
            String content = null;
            StringBuilder request = new StringBuilder();
            /****
             * 逐行读入；
             */
            while ((content = bufferedReader.readLine())!=null){
                request.append(content).append("\n");
                System.out.println("开始读取"+content);
            }

            byte[] response;
            if(httpCallback != null){
               response = httpCallback.onResponse(request.toString());
               if(mSocket != null && mSocket.isConnected()) {
                   send(response);

               }
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
            System.out.println("读取异常");

        }
    }
    private void send(byte[] response) throws IOException{
        /***
         * 拼接请求行
         * 请求头
         * 空行
         * 消息主体
         */
        String responseFirstLine = "HTTP/1.1 200 OK \n";
        String responseHead = "Content-type : text/html \n";
        OutputStream outputStream = mSocket.getOutputStream();
//        outputStream.write(responseFirstLine.getBytes(StandardCharsets.UTF_8));
//        outputStream.write(responseHead.getBytes(StandardCharsets.UTF_8));
//        outputStream.write("\n".getBytes(StandardCharsets.UTF_8));
        outputStream.write(response);
        if (mSocket != null && mSocket.isConnected()) {

            mSocket.close();
        }


    }
}
